package com.cgb2110.serve.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cgb2110.serve.mapper.MenuMapper;
import com.cgb2110.serve.pojo.Admin;
import com.cgb2110.serve.pojo.Menu;
import com.cgb2110.serve.service.IMenuService;
import com.cgb2110.serve.utils.AdminUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import sun.text.CollatorUtilities;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Larry
 * @since 2021-12-20
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Autowired
    private MenuMapper menuMapper;


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据用户id查询菜单列表
     * @return
     */
    @Override
    public List<Menu> getMenusByAdminId() {
        int adminID = AdminUtils.getCurrentAdmin().getId();
        ValueOperations<String,Object> valueOperations = redisTemplate.opsForValue();
        //从redis获取菜单数据
        List<Menu> menus = (List<Menu>) valueOperations.get("menu_"+adminID);
        //如果为空，去数据库获取
        if (CollectionUtils.isEmpty(menus)){
            menus = menuMapper.getMenusByAdminId(adminID);
            //将数据设置到redis中
            valueOperations.set("menu_"+adminID,menus );
        }
        return menus;

    }

    /**
     * 根据角色实现菜单列表
     * @return
     */
    @Override
    public List<Menu> getMenuswithRole() {
        List<Menu> list = menuMapper.getMenuswithRole();
        return  list;
    }
}
